/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.http.HttpResponse;
import java.text.SimpleDateFormat;

/**
 * <p>Project: smvc2022 - DownController
 * <p>Powered by webrx On 2022-04-07 09:21:18
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */

@RestController
public class DownController {

    @RequestMapping("/down")
    public void down(HttpServletRequest req, HttpServletResponse resp, HttpSession session){
        String filename = "g1.jpg";
        String f = "WEB-INF/down/"+filename;
        String ff = req.getServletContext().getRealPath(f);
        resp.setContentType("application/force-download");// 设置强制下载不打开
        resp.addHeader("Content-Disposition", "attachment;fileName=" + filename);// 设置文件名
        resp.setContentType("application/octet-stream");
        String path = req.getServletContext().getRealPath("/download/"); //文件下载源路径
        try(FileInputStream fis = new FileInputStream(ff);OutputStream os = resp.getOutputStream();) {
            byte[] buf = fis.readAllBytes(); //readAllBytes() java 9 新增的方法
            resp.addHeader("Content-Length", "" +buf.length);
            os.write(buf);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
